package com.bjsxt.livegoods.dao.user;

import com.bjsxt.livegoods.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

public class UserDaoImpl implements UserDao{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void saveUser(User user) {
        //检查用户是否存在
        Query query=new Query();
        query.addCriteria(Criteria.where("phone").is(user.getPhone()));
        List<User> users=mongoTemplate.find(query,User.class);
        if(users.size()!=0){
            //用户存在，更新
            Update update=new Update();
            update.set("yzm",user.getYzm());
            update.set("expire",user.getExpire());
            mongoTemplate.updateFirst(query,update,User.class);
        }else{
            //用户不存在
            mongoTemplate.insert(user);
        }
    }

    @Override
    public User findUserByPhone(String phone) {
        Query query=new Query();
        query.addCriteria(Criteria.where("phone").is(phone));
        List<User> users=mongoTemplate.find(query,User.class);
        if(users.size()==0){
            return null;
        }
        return users.get(0);
    }

    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }

    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
}
